const { ccclass, property, menu } = cc._decorator

/**
 * 自动加载资源组件
 */
@ccclass
@menu("component/AutoLoad")
export default class AutoLoad extends cc.Component {

    // 请填写对应的 bundle 名称
    @property()
    bundle: string = ""

    @property()
    protected _uuid: string = ""

    protected _prefab: cc.Prefab = null

    onEnable() {
        if (this._uuid.length === 0 || this._prefab) {
            return
        }

        cc.assetManager.loadAny(this._uuid, (err: Error, prefab: cc.Prefab) => {
            if (err) {
                cc.error("[AutoLoad]", this._uuid, err)
                return
            }

            if (!this.node.isValid) {
                return
            }

            prefab.addRef()
            this._prefab = prefab

            const node = cc.instantiate(prefab)
            node.parent = this.node
        })
    }

    onDestroy() {
        this._prefab?.decRef()
    }
}
